package com.ucode.search.crm.service.impl;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ucode.search.crm.model.ESFollowRecord;
import com.ucode.search.crm.service.ESFollowRecordService;
import com.ucode.springboot.starter.ESsearch.repository.ElasticsearchSearchTemplate;
import com.ucode.springboot.starter.ESsearch.repository.query.Advanc;
import com.ucode.springboot.starter.ESsearch.repository.query.PageSortHighLight;
import com.ucode.springboot.starter.ESsearch.repository.query.Sort;
import com.ucode.tool.base.Paginator;
import cn.hutool.core.util.StrUtil;

@Service
public class ESFollowRecordServiceImpl implements ESFollowRecordService {

    @Autowired
    private ElasticsearchSearchTemplate<ESFollowRecord, Long> esSearchTemplate;

    @Override
    public Paginator<ESFollowRecord> search(String keyword, Integer targetType, Long targetId,Long contactsId, Integer pageNum, Integer pageSize) throws Exception {
        BoolQueryBuilder queryBuilder = null;
        if(targetType.intValue() == 2){
            queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("customerId", targetId));
        }else{
            queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("targetId", targetId));
        }
        
        if(StrUtil.isNotBlank(keyword)){
            queryBuilder = queryBuilder.must(QueryBuilders.multiMatchQuery(keyword, "content","fileNames"));
        }
        
        if(contactsId != null && contactsId.longValue() != 0){
            queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("contactsId", contactsId));
        }
        
        PageSortHighLight pageSortHighLight = new PageSortHighLight(pageNum, pageSize);
        Advanc advanc = new Advanc();
        advanc.setPageSortHighLight(pageSortHighLight);
        advanc.setIncludes(new String[]{"id","customerId","contactsId","targetType","targetId","createUserId","fileIds","imgIds"});
        
        Sort.Order order = new Sort.Order(SortOrder.DESC,"id");
        pageSortHighLight.getSort().and(new Sort(order));
        
        return esSearchTemplate.search(queryBuilder, advanc, ESFollowRecord.class);
    }
    
}
